package com.xyht.sca_s.student_manage_system.modules.student_subsidies.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.CloseFlagConstant;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.SmsStudentSubsidiesApply;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.SmsStudentSubsidiesTask;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.req.SmsStudentSubsidiesTaskReq;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesApplyResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesTaskResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.mapper.SmsStudentSubsidiesApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.mapper.SmsStudentSubsidiesTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.service.SmsStudentSubsidiesTaskService;
import com.xyht.sca_s.student_manage_system.modules.tips.utils.TipsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.CloseFlagConstant.IS_CLOSE_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.ApplyStatusConstant.APPLY_STATUS_REJECT;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.CloseFlagConstant.IS_CLOSE_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.TaskRangeFlagConstant.TASK_RANGE_ALL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.AppNameConstant.APP_WEB_SUBSIDIES;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.CommonConstant.TIPS_SUBSIDIES_DESCRIPTION_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.CommonConstant.TIPS_SUBSIDIES_TITLE_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.TipsCloseFlagConstant.TIPS_CLOSE;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.TipsTypeConstant.TIPS_TYPE_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.UserTypeConstant.USER_TYPE_STUDENT;

/**
 * <p>
 * 学生助学金申请任务 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-02-26
 */
@Service
public class SmsStudentSubsidiesTaskServiceImpl extends ServiceImpl<SmsStudentSubsidiesTaskMapper, SmsStudentSubsidiesTask> implements SmsStudentSubsidiesTaskService {
    @Autowired
    private SmsStudentSubsidiesTaskMapper smsStudentSubsidiesTaskMapper;
    @Autowired
    private TipsUtil tipsUtil;
    @Autowired
    private SmsStudentSubsidiesApplyMapper smsStudentSubsidiesApplyMapper;


    @Override
    public ResponseResult addSubsidiesTask(SmsStudentSubsidiesTaskReq smsStudentSubsidiesTaskReq, String user_id) {
        if (isNullOrEmpty(smsStudentSubsidiesTaskReq.getTaskName())
                || isNullOrEmpty(smsStudentSubsidiesTaskReq.getTaskRange())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (smsStudentSubsidiesTaskReq.getTaskRange() != TASK_RANGE_ALL) {
            if (smsStudentSubsidiesTaskReq.getRangeId() == null || smsStudentSubsidiesTaskReq.getRangeId().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        SmsStudentSubsidiesTask smsStudentSubsidiesTask = new SmsStudentSubsidiesTask();
        BeanUtils.copyProperties(smsStudentSubsidiesTaskReq, smsStudentSubsidiesTask);
        smsStudentSubsidiesTask.setRangeId(smsStudentSubsidiesTaskReq.getRangeId().toString());
        smsStudentSubsidiesTask.setUserId(user_id);

        smsStudentSubsidiesTaskMapper.insert(smsStudentSubsidiesTask);

        //消息待办添加
        tipsUtil.addTips(TIPS_SUBSIDIES_TITLE_DEAL,
                TIPS_SUBSIDIES_DESCRIPTION_DEAL, //TIPS_LEAVE_DESCRIPTION_MESSAGE
                TIPS_TYPE_DEAL,
                APP_WEB_SUBSIDIES,
                smsStudentSubsidiesTaskReq.getTaskRange(), //RANGE_TYPE_ROLE
                smsStudentSubsidiesTaskReq.getRangeId().toString(),
                smsStudentSubsidiesTask.getId(),
                USER_TYPE_STUDENT,
                smsStudentSubsidiesTaskReq.getExpirationTime()
        );
        return CommonResult.success();
    }

    @Override
    public ResponseResult closeSubsidiesTask(SmsStudentSubsidiesTaskReq smsStudentSubsidiesTaskReq) {
        if (isNullOrEmpty(smsStudentSubsidiesTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesTask task = smsStudentSubsidiesTaskMapper.selectById(smsStudentSubsidiesTaskReq.getId());
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        SmsStudentSubsidiesTask smsStudentSubsidiesTask = new SmsStudentSubsidiesTask();
        smsStudentSubsidiesTask.setId(smsStudentSubsidiesTaskReq.getId());
        smsStudentSubsidiesTask.setIsClose(IS_CLOSE_TRUE);

        smsStudentSubsidiesTaskMapper.updateById(smsStudentSubsidiesTask);

        //关闭消息待办
        tipsUtil.finishTips(smsStudentSubsidiesTaskReq.getId(), null, TIPS_CLOSE);

        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteSubsidiesTask(SmsStudentSubsidiesTaskReq smsStudentSubsidiesTaskReq) {
        if (isNullOrEmpty(smsStudentSubsidiesTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesTask task = smsStudentSubsidiesTaskMapper.selectById(smsStudentSubsidiesTaskReq.getId());
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        List<SmsStudentSubsidiesApply> applyList = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, smsStudentSubsidiesTaskReq.getId()));
        if (applyList != null && applyList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_CAN_NOT_DELETE);
        }
        smsStudentSubsidiesTaskMapper.deleteById(smsStudentSubsidiesTaskReq.getId());

        //关闭消息待办
        tipsUtil.finishTips(smsStudentSubsidiesTaskReq.getId(), null, TIPS_CLOSE);

        return CommonResult.success();
    }

    @Override
    public ResponseResult updateSubsidiesTask(SmsStudentSubsidiesTaskReq smsStudentSubsidiesTaskReq) {
        if (isNullOrEmpty(smsStudentSubsidiesTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesTask subsidiesTask = smsStudentSubsidiesTaskMapper.selectById(smsStudentSubsidiesTaskReq.getId());
        if (subsidiesTask == null || subsidiesTask.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        //超时置位
        List<String> taskIDList = smsStudentSubsidiesTaskMapper.selectList(new QueryWrapper<SmsStudentSubsidiesTask>()
                .lambda()
                .eq(SmsStudentSubsidiesTask::getIsClose, IS_CLOSE_FALSE)
                .lt(SmsStudentSubsidiesTask::getExpirationTime, new Date()))
                .stream()
                .map(SmsStudentSubsidiesTask::getId)
                .collect(Collectors.toList());
        if (taskIDList.size() > 0) {
            SmsStudentSubsidiesTask outTimeTask = new SmsStudentSubsidiesTask();
            outTimeTask.setIsClose(CloseFlagConstant.IS_CLOSE_TRUE);
            smsStudentSubsidiesTaskMapper.update(outTimeTask, new QueryWrapper<SmsStudentSubsidiesTask>()
                    .lambda().in(SmsStudentSubsidiesTask::getId, taskIDList));
        }

        List<SmsStudentSubsidiesTask> closeTask = smsStudentSubsidiesTaskMapper.selectList(new QueryWrapper<SmsStudentSubsidiesTask>()
                .lambda().eq(SmsStudentSubsidiesTask::getId, smsStudentSubsidiesTaskReq.getId())
                .eq(SmsStudentSubsidiesTask::getIsClose, IS_CLOSE_TRUE));
        if (closeTask != null && closeTask.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_IS_CLOSED);
        }

        SmsStudentSubsidiesTask task = new SmsStudentSubsidiesTask();
        if (!isNullOrEmpty(smsStudentSubsidiesTaskReq.getTaskName())) {
            task.setTaskName(smsStudentSubsidiesTaskReq.getTaskName());
        }
        task.setId(smsStudentSubsidiesTaskReq.getId());
        smsStudentSubsidiesTaskMapper.updateById(task);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getSubsidiesTaskList(Integer pageNum, Integer pageSize, Integer is_close, String user_id,String search_str) {
//        if (isNullOrEmpty(is_close)) {
//            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
//        }

        //超时置位
        List<String> taskIDList = smsStudentSubsidiesTaskMapper.selectList(new QueryWrapper<SmsStudentSubsidiesTask>()
                .lambda()
                .eq(SmsStudentSubsidiesTask::getIsClose, IS_CLOSE_FALSE)
                .lt(SmsStudentSubsidiesTask::getExpirationTime, new Date()))
                .stream()
                .map(SmsStudentSubsidiesTask::getId)
                .collect(Collectors.toList());
        if (taskIDList.size() > 0) {
            SmsStudentSubsidiesTask outTimeTask = new SmsStudentSubsidiesTask();
            outTimeTask.setIsClose(CloseFlagConstant.IS_CLOSE_TRUE);
            smsStudentSubsidiesTaskMapper.update(outTimeTask, new QueryWrapper<SmsStudentSubsidiesTask>()
                    .lambda().in(SmsStudentSubsidiesTask::getId, taskIDList));
        }

        Page<SmsStudentSubsidiesTask> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsStudentSubsidiesTask> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(search_str)){
            queryWrapper.lambda().eq(SmsStudentSubsidiesTask::getTaskName,search_str);
        }
        if (!isNullOrEmpty(is_close)){
            queryWrapper.lambda().eq(SmsStudentSubsidiesTask::getIsClose, is_close);
        }
        queryWrapper.lambda()
                .eq(SmsStudentSubsidiesTask::getUserId, user_id)
                .orderByDesc(SmsStudentSubsidiesTask::getCreateTime);
        smsStudentSubsidiesTaskMapper.selectPage(page, queryWrapper);
        List<SmsStudentSubsidiesTaskResp> resultList = page.getRecords().stream().map(task -> {
            SmsStudentSubsidiesTaskResp taskResp = new SmsStudentSubsidiesTaskResp();
            BeanUtils.copyProperties(task, taskResp);

            Integer fill_num = smsStudentSubsidiesApplyMapper.selectCount(new QueryWrapper<SmsStudentSubsidiesApply>()
                    .lambda()
                    .eq(SmsStudentSubsidiesApply::getTaskId, task.getId()));
            Integer back_num = smsStudentSubsidiesApplyMapper.selectCount(new QueryWrapper<SmsStudentSubsidiesApply>()
                    .lambda()
                    .eq(SmsStudentSubsidiesApply::getTaskId, task.getId())
                    .eq(SmsStudentSubsidiesApply::getApplyStatus, APPLY_STATUS_REJECT));
            taskResp.setBackNum(back_num);
            taskResp.setFillNum(fill_num);
            return taskResp;
        }).collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(resultList, total);
    }

    @Override
    public ResponseResult getSubsidiesTaskDetail(String task_id, String user_id) {
        if (isNullOrEmpty(task_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesTask task = smsStudentSubsidiesTaskMapper.selectById(task_id);
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        SmsStudentSubsidiesTaskResp taskResp = new SmsStudentSubsidiesTaskResp();
        BeanUtils.copyProperties(task, taskResp);

        Integer fill_num = smsStudentSubsidiesApplyMapper.selectCount(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, task.getId()));
        Integer back_num = smsStudentSubsidiesApplyMapper.selectCount(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, task.getId())
                .eq(SmsStudentSubsidiesApply::getApplyStatus, APPLY_STATUS_REJECT));
        taskResp.setBackNum(back_num);
        taskResp.setFillNum(fill_num);

        List<SmsStudentSubsidiesApplyResp> applyRespList = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, taskResp.getId())
                .orderByDesc(SmsStudentSubsidiesApply::getCreateTime))
                .stream()
                .map(apply->{
                    SmsStudentSubsidiesApplyResp applyResp = new SmsStudentSubsidiesApplyResp();
                    BeanUtils.copyProperties(apply,applyResp);
                    return applyResp;
                })
                .collect(Collectors.toList());
        taskResp.setApplyList(applyRespList);
        return CommonResult.success(taskResp);
    }



}
